package com.lc.service.impl;

import com.lc.bean.Menu;
import com.lc.bean.Role;
import com.lc.bean.Users;
import com.lc.dao.RoleDao;
import com.lc.dao.UsersDao;
import com.lc.dao.impl.RoleDaoImpl;
import com.lc.dao.impl.UsersDaoImpl;
import com.lc.service.UsersService;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: ManolinCoder
 * @time: 2021/8/22
 */
public class UsersServiceImpl implements UsersService {
    private UsersDao usersDao = new UsersDaoImpl();
    private RoleDao roleDao = new RoleDaoImpl();
    @Override
    public Users login(String username, String password) {
        Users users = usersDao.login(username,password);
        if (users==null){
            return null;
        }

        //根据角色id查询角色菜单信息，便于展示相应菜单（三表联查）
        Integer roleId = users.getRoleId();
        Role role = roleDao.findRoleById(roleId);
        //此时取出的role中的菜单还是未分级的，所以下面需要对菜单进行分级
        List<Menu> menuList = role.getMenuList();
        List<Menu> newMenuList = new ArrayList<>();//保存分级后的菜单
        for (Menu menu : menuList) {
            if (menu.getUpmenuId()==0){//说明是一级菜单
                List<Menu> secondList = new ArrayList<>();
                for (Menu second : menuList) {
                    if (second.getUpmenuId()==menu.getMenuId()){//说明是这一类的二级菜单
                        secondList.add(second);
                    }
                }
                menu.setSecondMenuList(secondList);
                newMenuList.add(menu);
            }
        }
        role.setMenuList(newMenuList);
        users.setRole(role);
        return users;
    }

    @Override
    public List<Users> getUsersList(int pageIndex, int pageSize) {
        return usersDao.getUsersList(pageIndex,pageSize);
    }

    @Override
    public int total() {
        return usersDao.total();
    }

    @Override
    public List<Role> getRoleList() {
        return usersDao.getRoleList();
    }

    @Override
    public int insertUser(Users users) {
        return usersDao.insertUser(users);
    }
}
